package com.weizhi.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.weizhi.server.dto.SectionDto;
import com.weizhi.server.entity.Course;
import com.weizhi.server.entity.Section;
import com.weizhi.server.mapper.CourseMapper;
import com.weizhi.server.mapper.SectionMapper;
import com.weizhi.server.service.SectionService;
import com.weizhi.server.util.PropertyCopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SectionServiceImpl implements SectionService {
    private final static Logger logger = LoggerFactory.getLogger(SectionServiceImpl.class);

    @Resource
    private SectionMapper sectionMapper;
    @Resource
    private CourseMapper courseMapper;

    @Override
    public PageInfo list(JSONObject param) {
        Section section = new Section();
        section.setCourseId(param.getLong("courseId"));
        section.setChapterId(param.getLong("chapterId"));
        PageHelper.startPage(param.getInteger("pageIndex"), param.getInteger("pageSize"));
        List<Section> sectionList = sectionMapper.selectSelective(section);
        PageInfo pageInfo = new PageInfo(sectionList);
        List<SectionDto> sectionDtoList = PropertyCopyUtil.copyList(sectionList, SectionDto.class);
        pageInfo.setList(sectionDtoList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public void save(SectionDto sectionDto) {
        Section section = new Section();
        BeanUtils.copyProperties(sectionDto, section);
        if(section.getId() == null){
            sectionMapper.insertSelective(section);
        }else{
            sectionMapper.updateByPrimaryKey(section);
        }
        //更新课程的总时长
        courseMapper.updateTotalTime(section.getCourseId());
    }

    @Override
    @Transactional(rollbackFor = {Exception.class, RuntimeException.class})
    public void delete(Long id) {
        Section section = sectionMapper.selectByPrimaryKey(id);
        sectionMapper.deleteByPrimaryKey(id);
        //更新课程的总时长
        courseMapper.updateTotalTime(section.getCourseId());
    }
}
